const Router = require('@koa/router');
const { User } = require('../databases');
const bcrypt = require('bcrypt');
const userSchema = require('../schemas/userSchema');
const jwt = require('jsonwebtoken');
const jwtCheck = require('../middewares/jwtcheck');
const validate = require('../middewares/validate');
const userRouter = new Router({
    prefix: '/user'
});

userRouter.get('/list', jwtCheck, async (ctx, next) => {
    const users = await User.findAll();
    ctx.body = {
        code: 200,
        message: 'User home page',
        data: users,
    };
    return;
});

userRouter.post('/add', validate(userSchema),async (ctx, next) => {
    const { username, password, tel, email } = ctx.validatedBody;
    const hashePassword = await bcrypt.hash(password, 10);
    const avatar = ctx.files[0].filename; // 上传的文件名
    const currentUser = await User.create({
        username,
        password: hashePassword,
        tel,
        email,
        avatar: avatar,
    });
    ctx.body = {
        message: 'Add User page',
        data: currentUser,
    }
});


userRouter.post('/login', async (ctx, next) => {
  const { username, password } = ctx.request.body;

  const currentUser = await User.findOne({ where: { username } });
  if (!currentUser) {
    ctx.body = {
      code: 500,
      message: 'User not found'
    };
    return;
  }

  const passwordMatch = await bcrypt.compare(password, currentUser.password);

  if (!passwordMatch) {
    ctx.body = {
      code: 500,
      message: 'Incorrect password'
    };
    return;
  }

  const token  =
    // "Bearer " +
    jwt.sign(
      {
        userId: currentUser.uid,
        username: currentUser.username,
      },
      "scx123",
      {
        expiresIn: 3600 * 24 * 7, // 7天过期
      }
    );
  ctx.body = {
    success: true,
    message: 'login success',
    data: { 
      token: 'Bearer ' + token, 
      userInfo: {
      uid: currentUser.uid,
      username: currentUser.username,
      tel: currentUser.tel,
      email: currentUser.email,
      avatar: currentUser.avatar || ''
    }  }
  };
  return

});

module.exports = userRouter;